#!/usr/bin/perl
################################################################################
#
# Runs the ePub-to-Kindle converter.
#
#   epub2Kindle.pl <folderContainingEpubFile>
#
# Note that this has been set up to use Calibre as the converter.  It will
# need tailoring if you wish to use another program -- see the bit at !!!.
#
# It also assumes that we are running within a "standard" folder structure,
# so that the output needs to be generated in a particular location relative
# to the input.
################################################################################

#-------------------------------------------------------------------------------
use strict;
use warnings;
use Cwd 'abs_path';
use File::Basename;
use File::Copy;
use File::Spec;



#-------------------------------------------------------------------------------
my $inputFolder = $ARGV[0];
my $scriptFolder = dirname(File::Spec->rel2abs( __FILE__ ));




#-------------------------------------------------------------------------------
chdir $inputFolder;
my @epub = <*.epub>;
my $n = @epub;
if (1 != $n) { die "Input folder must contain precisely one ePub file."; }



#-------------------------------------------------------------------------------
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
# You may need to tailor the lines below for other converters.
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#-------------------------------------------------------------------------------
my $converter;
my $args = "$epub[0] .mobi";
if (-e File::Spec->catfile(abs_path("$scriptFolder"), "target.location"))
{
  open FILE, "<", File::Spec->catfile(abs_path("$scriptFolder"), "target.location");
  $converter = <FILE>;
  $converter =~ s/^\s+//;
  $converter =~ s/\s+$//;
  close FILE;
}
else
{
  $converter = File::Spec->catfile(abs_path("$scriptFolder"), "epub2Kindle");
}



#-------------------------------------------------------------------------------
my $status = system("\"$converter\" $args");
if (0 != ($status >> 8)) { die "Conversion failed"; }



#-------------------------------------------------------------------------------
my @mobi = <*.mobi>;
$n = @mobi;
if (1 != $n) { die "No mobi file created."; }
move($mobi[0], "../../Kindle/output/$mobi[0]");



#-------------------------------------------------------------------------------
print "Processing completed successfully";
